package com.example.filter;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.response.R;
import com.example.service.impl.LoginAccountInfo;
import com.example.utils.JwtTokenUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtLoginTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取Token
        String token = request.getHeader("token");
        if (token == null) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }

        //解析Token
        String account = JwtTokenUtil.getAccount(token);

        //从redis中获取用户信息
        String redisKey = account;
        LoginAccountInfo accountInfo = (LoginAccountInfo) redisTemplate.opsForValue().get(redisKey);
        System.out.println(accountInfo);
        if (ObjectUtils.isEmpty(accountInfo)) {
            //用户未登录
            R result = R.fail("用户未登录");
            String str = JSONObject.toJSONString(result);
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(str);
            return;
        }


        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(accountInfo, null, accountInfo.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);


        //放行
        filterChain.doFilter(request, response);
    }
}